﻿using System;
using System.Net;
using System.Windows;
using Microsoft.Phone.Controls;

namespace geopg_wp7
{
    public partial class LoginPage : PhoneApplicationPage
    {
        public string usrname;
        public string pword;
        public LoginPage()
        {
            InitializeComponent();
            // Fill in user-data if saved setting is existing
            if (System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Contains("user") && System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Contains("pass") && System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Contains("check"))
            {
                usernameBox.Text = (string)System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["user"];
                passwordBox.Password = (string)System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["pass"];
                checkBox_login.IsChecked = (bool)System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings["check"];
                loginButton.IsEnabled = false;
                registerButton.IsEnabled = false;
                login();
            }
        }
        
        void GetRequestStreamCallback(IAsyncResult asynchronousResult)
        {
            // Dispatcher fixes SystemAuthorizationException for string postData
            this.Dispatcher.BeginInvoke(delegate()
            {
                // Start ProgressBar
                loginProgress.Visibility = Visibility.Visible;
                // Make TextBox uneditable for login-time
                usernameBox.IsEnabled = false;
                passwordBox.IsEnabled = false;
                checkBox_login.IsEnabled = false;
                loginButton.IsEnabled = false;
                registerButton.IsEnabled = false;
                // Create WebRequest
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                // Open Stream
                System.IO.Stream postStream = request.EndGetRequestStream(asynchronousResult);
                // String we post to the servlet
                string postData = usrname + pword;/*"user=" + usernameBox.Text + "&password=" + passwordBox.Password;*/
                // Convert string to byte-array
                byte[] byteArray = System.Text.Encoding.UTF8.GetBytes(postData);
                // Send byte-array via Stream
                postStream.Write(byteArray, 0, byteArray.Length);
                postStream.Close();
                // Request response
                request.BeginGetResponse(new AsyncCallback(GetResponseCallback), request);
            });
        }

        void GetResponseCallback(IAsyncResult asynchronousResult)
        {
            try
            {
                // Create request
                HttpWebRequest request = (HttpWebRequest)asynchronousResult.AsyncState;
                // Create response
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asynchronousResult);



                // Open ResponseStream
                System.IO.Stream streamResponse = response.GetResponseStream();
                // Read the Stream and put output to String
                System.IO.StreamReader streamReader = new System.IO.StreamReader(streamResponse);
                string responseString = streamReader.ReadToEnd();
                // Dispatcher fixes SystemAuthorizationException for String responseString
                this.Dispatcher.BeginInvoke(delegate()
                {

                    foreach (Cookie cook in response.Cookies)
                    {
                        MessageBox.Show("Cookie: " +
                        cook.Name + " " + cook.Value +
                        "\nDomain: " + cook.Domain +
                        "\nPath: " + cook.Path +
                        "\nPort: " + cook.Port +
                        "\nSecure: " + cook.Secure +

                        "\nWhen issued: " + cook.TimeStamp +
                        "\nExpires: (expired?) " +
                            cook.Expires + " " + cook.Expired +
                        "\nDon't save: " + cook.Discard +
                        "\nComment: " + cook.Comment +
                        "\nUri for comments: " + cook.CommentUri +
                            // Show the string representation of the cookie.
                        "\nString: " + cook.ToString());
                        GlobalVariables.cookie = cook.ToString();
                    }

                    // Artificial waiting-time for ProgressBar
                    //System.Threading.Thread.Sleep(2500);
                    // Stop ProgressBar
                    loginProgress.Visibility = Visibility.Collapsed;
                    // Make TextBox editable after login-procedure
                    usernameBox.IsEnabled = true;
                    passwordBox.IsEnabled = true;
                    checkBox_login.IsEnabled = true;
                    loginButton.IsEnabled = true;
                    registerButton.IsEnabled = true;
                    // Output is the position of the string. If it doesn't exist, its position is "-1"
                    if (responseString.IndexOf("cause") != -1)
                    {
                        if (responseString.IndexOf("cause=\"0\"") != -1)
                            MessageBox.Show("Internal Error (SQL)");
                        else if (responseString.IndexOf("cause=\"1\"") != -1)
                            MessageBox.Show("Expected POST but got GET request.");
                        else if (responseString.IndexOf("cause=\"10\"") != -1)
                            MessageBox.Show("Please enter a username.");
                        else if (responseString.IndexOf("cause=\"11\"") != -1)
                            MessageBox.Show("Please enter a password.");
                        else if (responseString.IndexOf("cause=\"7\"") != -1)
                            MessageBox.Show("User does not exist.");
                        else if (responseString.IndexOf("cause=\"5\"") != -1)
                            MessageBox.Show("Wrong password.");
                        else if (responseString.IndexOf("cause=\"4\"") != -1)
                            MessageBox.Show("Not enough privileges to perform action.");
                        else
                            MessageBox.Show("An unexpected error occured.");
                        // More Error-Codes to be done!
                    }
                    else
                    {
                        MessageBox.Show("Login successful.");
                        NavigationService.Navigate(new Uri("//MainPage.xaml", UriKind.Relative));
                    }
                });
                streamResponse.Close();
                streamReader.Close();
                response.Close();
            }
            catch (WebException e)
            {
                this.Dispatcher.BeginInvoke(delegate()
                {
                    MessageBox.Show("Can't establish connection. Starting offline-mode.");
                    NavigationService.Navigate(new Uri("//MainPage.xaml", UriKind.Relative));
                });
            }
        }

        // Seperate login-method so we can automatically login on start-up
        private void login()
        {
            usrname = "";
            pword = "";
            if (usernameBox.Text != "")
                usrname = "user=" + usernameBox.Text;
            if (passwordBox.Password != "")
                pword = "&password=" + passwordBox.Password;
            //MessageBox.Show(usrname + "  -  " + pword);
            usernameBox.IsEnabled = false;
            passwordBox.IsEnabled = false;
            // URL of the Servlet
            Uri address = new Uri("http://geopg.de/backend/UserLogIn");
            HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
            request.CookieContainer = new CookieContainer();
            // Set request-method and content-type
            request.Method = "POST";
            request.ContentType = "application/x-www-form-urlencoded";
            // Do the request
            request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
            usernameBox.IsEnabled = true;
            passwordBox.IsEnabled = true;
        }

        private void loginButton_Click(object sender, RoutedEventArgs e)
        {

            // Call login-method
            login();

            // Save User and Pass, if CheckBox is checked!
            if (checkBox_login.IsChecked == true && !(bool)System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Contains("check"))
            {
                // Remove old setting
                System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Remove("user");
                // Add new setting
                System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Add("user", usernameBox.Text);
                // Remove old setting
                System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Remove("pass");
                // Add new setting
                System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Add("pass", passwordBox.Password);
                // Remove old setting
                System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Remove("check");
                // Add new setting
                System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Add("check", true);
                // Save the setting
                System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Save();
                MessageBox.Show("User-Data saved.");
            }
        }

        private void registerButton_Click(object sender, RoutedEventArgs e)
        {
            NavigationService.Navigate(new Uri("//RegisterPage.xaml", UriKind.Relative));
        }

        private void mainPage_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//MainPage.xaml", UriKind.Relative));
        }

        private void localPictures_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//LocalPicturesPage.xaml", UriKind.Relative));
        }

        private void settings_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//SettingsPage.xaml", UriKind.Relative));
        }

        private void info_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//InfoPage.xaml", UriKind.Relative));
        }

        public void register_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//RegisterPage.xaml", UriKind.Relative));
        }

        public void logout_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("//LogoutPage.xaml", UriKind.Relative));
        }
    }
}